<?php

namespace Yolo\Utils;

use Exception;

class CrontabUtil
{
    public static function getNextRunTime(array $config): int
    {
        if (isset($config['interval'])) {
            return $config['interval'];
        }

        if (!isset($config['every'])) {
            return 3600;
        }

        $every = $config['every'];

        $now = time();
        $nextTime = $now;

        switch ($every[0]) {
            case 'minute':

                $nextTime = date('Y-m-d H:i', strtotime("+$every[1] minutes", $now)) . ':00';
                break;
            case 'hour':

                $nextTime = date('Y-m-d H', strtotime("+$every[1] hours", $now)) . ':00:00';
                if (isset($every[2]) && $every[2] > 0) {
                    $nextTime = date('Y-m-d H:i', strtotime("+$every[2] minutes", strtotime($nextTime))) . ':00';
                }

                break;
            case 'day':

                $nextTime = date('Y-m-d', strtotime("+$every[1] days", $now)) . ' 00:00:00';
                if (isset($every[2]) && $every[2] > 0) {
                    $nextTime = date('Y-m-d H', strtotime("+$every[2] hours", strtotime($nextTime))) . ':00:00';
                }

                if (isset($every[3]) && $every[3] > 0) {
                    $nextTime = date('Y-m-d H:i', strtotime("+$every[3] minutes", strtotime($nextTime))) . ':00';
                }

                break;
        }

        $seconds = strtotime($nextTime) - $now;

        return $seconds > 0 ? $seconds : 3600;
    }
}
